package cn.hdu.community.controller;

import cn.hdu.community.dto.Result;
import cn.hdu.community.entity.Article;
import cn.hdu.community.service.ArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author zhangxin
 * @since 2022-04-08
 */
@RestController
@RequestMapping("/article")
public class ArticleController {

    @Autowired
    private ArticleService articleService;
    @Autowired
    private HttpServletRequest request;

    /**
     * 发布文章
     *
     * @param article
     * @return
     */
    @RequestMapping("/writeArticle")
    public Result writeArticle(@RequestBody Article article) {
        Integer userId = (Integer) request.getAttribute("userId");
        Article newArticle = articleService.insertArticle(userId, article);
        if (newArticle != null) {
            return Result.success("发布成功", newArticle);
        } else {
            return Result.internalError(null);
        }
    }

    /**
     * 获取属于该用户的全部文章
     *
     * @return
     */
    @RequestMapping("/getArticle")
    public Result getArticle() {
        Integer userId = (Integer) request.getAttribute("userId");
        List<Article> article = articleService.getAllArticleByAuthorId(userId);
        if (article != null) {
            return Result.success("获取成功", article);
        } else {
            return Result.internalError(null);
        }

    }

    /**
     * 文章修改
     *
     * @param newArticle
     * @return
     */
    @RequestMapping("/modifyArticle")
    public Result modifyArticle(@RequestBody Article newArticle) {
        LocalDateTime modifyTime = LocalDateTime.now();
        newArticle.setArticleModifyTime(modifyTime);
        if (articleService.updateById(newArticle)) {
            return Result.success("修改成功", articleService.getById(newArticle.getArticleId()));
        } else {
            return Result.internalError(null);
        }
    }

    /**
     * 删除文章
     *
     * @param articleId
     * @return
     */
    @RequestMapping("/deleteArticle")
    public Result deleteArticle(@RequestParam("articleId") Integer articleId) {
        if (articleService.removeById(articleId)) {
            return Result.success("删除成功", null);
        } else {
            return Result.internalError(null);
        }
    }
}
